/*
 * DynamicAction.java
 *
 * Created on March 27, 2005, 12:47 AM
 */

package tools;

import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;

/**
 *
 * @author Keith
 */
public class DynamicAction extends AbstractAction implements PropertyChangeListener {
  
  private Action action;

  public DynamicAction( String name ){
    this( name, (Action)null );
  }

  public DynamicAction( String name, Icon icon ) {
    this( name, icon, (Action)null );
  }

  public DynamicAction( String name, Action a ) {
    super( name );

    setAction( a );
  }

  public DynamicAction( String name, Icon icon, Action a ) {
    super( name, icon );

    setAction( a );
  }

  public void actionPerformed( ActionEvent e ){
    if ( action != null ){
      action.actionPerformed( e );
    }
  }

  protected void copyValue( String key, Action src ){
    putValue( key, ( src == null ? null : src.getValue( key ) ) );
  }

  public void setAction( Action a ) {
    if ( action != null ){
      action.removePropertyChangeListener( this );
    }

    action = a;

    copyValue( SHORT_DESCRIPTION, action );

    setEnabled( action != null ? action.isEnabled() : false );

    if ( action != null ){
      action.addPropertyChangeListener( this );
    }
  }

  public Action getAction() {
    return action;
  }

  public void propertyChange( PropertyChangeEvent e ) {
    String propName = e.getPropertyName();

//    System.out.println( getValue( NAME ) + ": " + propName );
    if ( ! propName.equals( NAME ) &&
           ! propName.equals( AbstractAction.ACCELERATOR_KEY ) &&
           ! propName.equals( AbstractAction.MNEMONIC_KEY ) &&
           ! propName.equals( AbstractAction.SMALL_ICON )
           ){
      firePropertyChange( propName, e.getOldValue(), e.getNewValue() );
    }
  }
}
